package com.cooge.jiexi;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;

@SuppressWarnings("deprecation")
public class NetUtil {
	
	private static int trynum = 0;
	public static String getAutoHtml(String url,String charsetName,Header ...header)throws Exception{
		String html = null;
		try {
		   html = NetUtil.getHtml(url,charsetName ,header);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(trynum>10){
			if(NetUtil.isNet()){
				trynum=0;
			}else{
				/////////无网络休息十分钟/////////////////
				while(true){
					System.out.println("无网络休息中。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。");
					Thread.sleep(600000);
					if(trynum==0||NetUtil.isNet()){
						break;
					}
				}
			}
		}
		if(html == null){
			trynum++;
			throw new NullPointerException("没有获取数据");
		}else{
			trynum=0;
		}
		return html;
		
		
	}
	
	
	
	public static String getAutoHtml(String url,Header ...header) throws Exception{
		String html = null;
		try {
		   html = NetUtil.getHtml(url, header);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(trynum>10){
			if(NetUtil.isNet()){
				trynum=0;
			}else{
				/////////无网络休息十分钟/////////////////
				while(true){
					System.out.println("无网络休息中。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。");
					Thread.sleep(600000);
					if(trynum==0||NetUtil.isNet()){
						break;
					}
				}
				////////////////////////////////////////
			}
		}
		if(html == null){
			trynum++;
			throw new NullPointerException("没有获取数据");
		}else{
			trynum=0;
		}
		return html;
	}
	
	public static boolean isNet(){
		try {
			System.out.println("测试网络中。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。");
			String html = NetUtil.getHtml("http://m.baidu.com/?pu=sz%401321_480&wpo=btmfast");
			if(html!=null&&html.length()>100){
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public static String getHtml(String url) throws Exception{
		HttpClient	httpclient  = new DefaultHttpClient();
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 6000);
		HttpGet httpget = new HttpGet(url);
			HttpResponse response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			InputStream in = entity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while((line = reader.readLine()) != null){
				sb.append(line + "\r\n"); 
			}
			return sb.toString();
	}
	
	public static String getHtml(String url,Header ...header) throws Exception{
			HttpClient	httpclient  = new DefaultHttpClient();
			httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 6000);
			HttpGet httpget = new HttpGet(url);
			httpget.setHeaders(header);
			HttpResponse response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			InputStream in = entity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in,"utf-8"));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while((line = reader.readLine()) != null){
				sb.append(line + "\r\n"); 
			}
			in.close();
			return sb.toString();
	}
	public static String getHtml(String url,String charsetName,Header ...header) throws Exception{
		HttpClient	httpclient  = new DefaultHttpClient();
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 6000);
		HttpGet httpget = new HttpGet(url);
		httpget.setHeaders(header);
		HttpResponse response = httpclient.execute(httpget);
		HttpEntity entity = response.getEntity();
		InputStream in = entity.getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in,charsetName));
		StringBuilder sb = new StringBuilder();
		String line = null;
		while((line = reader.readLine()) != null){
			sb.append(line + "\r\n"); 
		}
		//System.out.println(sb.toString());
		return sb.toString();
}
	
	public static String getGZIPHtml(String url,String charsetName,Header ...header) throws Exception{
		HttpClient	httpclient  = new DefaultHttpClient();
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 6000);
		HttpGet httpget = new HttpGet(url);
		httpget.setHeaders(header);
		HttpResponse response = httpclient.execute(httpget);
		HttpEntity entity = response.getEntity();
		InputStream in = entity.getContent();
		in = new GZIPInputStream(in); 
		BufferedReader reader = new BufferedReader(new InputStreamReader(in,charsetName));
		StringBuilder sb = new StringBuilder();
		String line = null;
		while((line = reader.readLine()) != null){
			sb.append(line + "\r\n"); 
		}
		//System.out.println(sb.toString());
		return sb.toString();
}
	
	public static String getGZIPHtml(String url,Header ...header) throws Exception{
		return  getGZIPHtml(url,"UTF-8",header);
}
	
	
	
	public static String postHtml(String url,Map<String,String>  m,Header ...header) throws Exception{
		HttpClient	httpclient  = new DefaultHttpClient();
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 6000);
			HttpPost httppost = new HttpPost(url);
			httppost.setHeaders(header);
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			Iterator<Entry<String, String>>	iterator =  m.entrySet().iterator();
			while(iterator.hasNext()){
				Entry<String, String> me = iterator.next();
				NameValuePair nameValuePair = new BasicNameValuePair(me.getKey(), me.getValue());
				list.add(nameValuePair);
			}
			HttpEntity requestenEntity = new UrlEncodedFormEntity(list);
			httppost.setEntity(requestenEntity);
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			InputStream in = entity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while((line = reader.readLine()) != null){
				sb.append(line + "\r\n"); 
			}
			return sb.toString();
	}
	
	
	private HashMap<String, String> headermap = new HashMap<String, String>();
	
	private Header[] headers;

	public Header[] getHeaders() {
		return headers;
	}
	public String getHeader(String key) {
		return headermap.get(key);
	}

	public void setHeaders(Header[] headers) {
		headermap.clear();
		for(Header h:headers){
			headermap.put(h.getValue(), h.getValue());
		}
		this.headers = headers;
	}
	
	public String responseUrl;
	
	
	public String getResponseUrl() {
		return responseUrl;
	}
	public void setResponseUrl(String responseUrl) {
		this.responseUrl = responseUrl;
	}
	public InputStream getInputStream(String url, Header... header)throws Exception {
		
		HttpContext httpContext = new BasicHttpContext();
		HttpClient	httpclient  = new DefaultHttpClient();
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 6000);
		HttpGet httpget = new HttpGet(url);
		httpget.setHeaders(header);
		HttpResponse response = httpclient.execute(httpget,httpContext);
		HttpHost targetHost = (HttpHost)httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
		HttpUriRequest realRequest = (HttpUriRequest)httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);
        this.setResponseUrl(targetHost+""+realRequest.getURI());
		HttpEntity entity = response.getEntity();
		this.setHeaders(response.getAllHeaders());
		InputStream in = entity.getContent();
		return in;
	}
	
	
	
	
	public static String getHtml(InputStream in) throws Exception {
		BufferedReader reader = new BufferedReader(new InputStreamReader(in,
				"UTF-8"));
		StringBuilder sb = new StringBuilder();
		String line = null;
		while ((line = reader.readLine()) != null) {
			sb.append(line + "\r\n");
		}
		return sb.toString();
	}
	public  String postHtml(String url,String addition,Header ...header) throws Exception{
		HttpClient	httpclient  = new DefaultHttpClient();
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 6000);
		HttpPost httppost = new HttpPost(url);
		httppost.setHeaders(header);
		HttpEntity requestenEntity = new StringEntity(addition,"utf-8");
		httppost.setEntity(requestenEntity);
		HttpResponse response = httpclient.execute(httppost);
		HttpEntity entity = response.getEntity();
		this.setHeaders(response.getAllHeaders());
		InputStream in = entity.getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
		StringBuilder sb = new StringBuilder();
		String line = null;
		while((line = reader.readLine()) != null){
			sb.append(line + "\r\n"); 
		}
		return sb.toString();
}
	
	
	public static String format(String ...values){
		String str = values[0];
		for(int i=1;i<values.length;i++){
			str = 	str.replace("%s", values[i]);
		}
		return str;
	}
	
	public static String md5(String s){
		
			char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
			char str[];
			byte strTemp[]=s.getBytes();
			
			MessageDigest mdTemp;
			try {
				mdTemp = MessageDigest.getInstance("MD5");
				mdTemp.update(strTemp);
				byte md[]=mdTemp.digest();
				int j=md.length;
				str=new char[j*2];
				int k=0;
				for(int i=0;i<j;i++){
					byte byte0=md[i];
					str[k++]=hexDigits[byte0>>>4&0xf];
					str[k++]=hexDigits[byte0&0xf];
				}
				return new String(str);
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		public static void main(String[] args) {
			
			System.out.println(NetUtil.isNet());
			
		}
	}
